from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from favorite.models import UserFavorite, UserFavoriteFolder
from posts.models import Post
from users.models import UserInfo


class UserFavoriteFoldAddSerializer(serializers.ModelSerializer):
    """给收藏夹添加帖子"""

    folder = serializers.PrimaryKeyRelatedField(
        queryset=UserFavoriteFolder.objects.all(),
        source='UserFavoriteFolder',
        write_only=True,
        help_text='收藏夹id'
    )

    post = serializers.PrimaryKeyRelatedField(
        queryset=Post.objects.all(),
        source='Post',
        write_only=True,
        help_text='帖子id'
    )

    def create(self, validated_data):

        folder_id = validated_data['UserFavoriteFolder'].id
        post_id = validated_data['Post'].id

        post_set = UserFavorite.objects.all().filter(folder_id=folder_id)
        for i in post_set:
            if post_id == i.post_id:
                raise ValidationError('当前文件夹下有相同的收藏了')

        instance = UserFavorite.objects.create(folder_id=folder_id, post_id=post_id)
        instance.save()

        return instance

    class Meta:
        model = UserFavorite
        fields = ['id', 'folder', 'post']


class UserFavoriteFoldSerializer(serializers.ModelSerializer):
    """新增收藏夹"""

    user_id = serializers.PrimaryKeyRelatedField(
        queryset=UserInfo.objects.all(),
        source='user',
        write_only=True,
        help_text='用户id'
    )

    class Meta:
        model = UserFavoriteFolder
        fields = ['id', 'folder_name', 'user_id']

    def validate_folder_name(self, value):
        """
        判断文件夹名是否为null
        判断收藏夹是否重复
        判断收藏夹数量是否超过数量
        """

        if value is None:
            raise serializers.ValidationError('文件夹名不能为空')

        user_id = self.context['request'].data['user_id']  # 获取当前添加收藏夹用户的id
        query_set = UserFavoriteFolder.objects.filter(user=user_id)

        count = query_set.count()
        if count >= 100:
            raise serializers.ValidationError('收藏夹数量超过上限')

        folder_count = query_set.filter(folder_name=value).count()
        if folder_count >= 1:
            raise serializers.ValidationError('收藏夹已存在')
        return value


class UserFavoriteBaseSerializer(serializers.ModelSerializer):
    """帖子序列化器"""

    class UserFavoritePostSerializer(serializers.ModelSerializer):
        """将文章id修改为url"""
        title = serializers.CharField(read_only=True)

        class Meta:
            model = Post
            fields = ['id', 'title']

        def to_representation(self, instance):
            res = super().to_representation(instance=instance)
            res['suffix'] = 'post-manage/posts/' + str(res['id']) + '/'
            del res['id']
            return res

    post = UserFavoritePostSerializer(required=False)

    class Meta:
        model = UserFavorite
        fields = ['id', 'post']


class UserFavoriteFoldDetailSerializer(serializers.ModelSerializer):
    """
    显示一个收藏夹的所有文章
    删除, 修改收藏夹文件名
    """

    favorite_set = UserFavoriteBaseSerializer(many=True, read_only=True)

    class Meta:
        model = UserFavoriteFolder
        fields = ['id', 'folder_name', 'favorite_set']
